package com.isoft.c2team3service2.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.isoft.c2team3service2.entity.UserMessage;
import com.isoft.c2team3service2.entity.UserMessageVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface UserMessageMapper extends BaseMapper<UserMessage> {
    // 查询两个用户之间的会话（按时间倒序）
//    @Select("""
//        SELECT m.*, u.nick_name AS senderNickName, h.photourl AS senderPhotoUrl, s.is_read AS isRead
//        FROM user_message m
//        LEFT JOIN tb_login ul ON m.sender_id = ul.id
//        LEFT JOIN tb_person u ON ul.id = u.id
//        LEFT JOIN tb_head h ON ul.email = h.email
//        LEFT JOIN user_message_status s ON m.id = s.message_id AND s.receiver_id = #{currentUserId}
//        WHERE (m.sender_id = #{userId1} AND m.receiver_id = #{userId2})
//           OR (m.sender_id = #{userId2} AND m.receiver_id = #{userId1})
//        ORDER BY m.create_time DESC
//        LIMIT #{limit} OFFSET #{offset}
//        """)
    @Select("""
        SELECT m.*, u.nick_name AS senderNickName, h.photo AS senderPhotoUrl, s.is_read AS isRead
        FROM user_message m
        LEFT JOIN tb_login ul ON m.sender_id = ul.id
        LEFT JOIN tb_person u ON ul.id = u.id
        LEFT JOIN tb_head h ON ul.email = h.email
        LEFT JOIN user_message_status s ON m.id = s.message_id AND s.receiver_id = #{userId1}
        WHERE (m.sender_id = #{userId1} AND m.receiver_id = #{userId2})
           OR (m.sender_id = #{userId2} AND m.receiver_id = #{userId1})
        ORDER BY m.create_time DESC
        LIMIT #{limit} OFFSET #{offset}
        """)
    List<UserMessageVO> selectConversation(Integer userId1, Integer userId2, Integer limit, Integer offset);

    // 查询未回复的消息数（用于限制未关注用户的发送）
    @Select("""
        SELECT COUNT(1) FROM user_message m
        WHERE m.sender_id = #{senderId} AND m.receiver_id = #{receiverId}
          AND NOT EXISTS (
              SELECT 1 FROM user_message m2
              WHERE m2.sender_id = #{receiverId} AND m2.receiver_id = #{senderId}
                AND m2.create_time > m.create_time
          )
        """)
    Integer countUnrepliedMessages(Integer senderId, Integer receiverId);
    // 新增：批量更新消息状态（未读→已读）
    @Update("<script>" +
            "UPDATE user_message SET status = #{status} " +
            "WHERE id IN " +
            "<foreach collection='messageIds' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateStatus(@Param("messageIds") List<Integer> messageIds, @Param("status") Integer status);
    /**
     * 新增：查询当前用户收到的消息（分页+可选状态筛选）
     * @param receiverId 当前登录用户ID（接收者）
     * @param status 消息状态（可选：0-未读，1-已读，null-查所有）
     * @param limit 页大小
     * @param offset 分页偏移量（(page-1)*size）
     * @return 消息列表（含发送者信息）
     */

    @Select("<script>" +
            "SELECT " +
            "    m.*, " +
            "    p.nick_name AS senderNickName, " + // 移除行内注释，或移到单独行
            "    h.photo AS senderPhotoUrl, " +
            "    s.is_read AS isRead " +
            "FROM user_message m " +
            "LEFT JOIN tb_login ul ON m.sender_id = ul.id " +
            "LEFT JOIN tb_person p ON ul.email = p.email " + // 已修正为email关联
            "LEFT JOIN tb_head h ON ul.email = h.email " +
            "LEFT JOIN user_message_status s ON m.id = s.message_id AND s.receiver_id = #{receiverId} " +
            "WHERE m.receiver_id = #{receiverId} " +
            "    <if test='status != null'>AND m.status = #{status}</if> " +
            "ORDER BY m.create_time DESC " +
            "LIMIT #{limit} OFFSET #{offset}" +
            "</script>")
    List<UserMessageVO> selectReceivedMessages(
            @Param("receiverId") Integer receiverId,
            @Param("status") Integer status,
            @Param("limit") Integer limit,
            @Param("offset") Integer offset);
    /**
     * 同样检查countReceivedMessages方法，确保只有一个@Select注解
     */
    @Select("<script>" +
            "SELECT COUNT(1) " +
            "FROM user_message m " +
            "WHERE m.receiver_id = #{receiverId} " +
            "    <if test='status != null'>AND m.status = #{status}</if> " +
            "</script>")
    Long countReceivedMessages(
            @Param("receiverId") Integer receiverId,
            @Param("status") Integer status);
}